package com.halflife.comeElectricity.member.merchant;

import com.halflife.shiro.utils.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhaoyf on 2018/2/4.
 */
@RestController
@RequestMapping("mc_merchant")
public class MerchantController {
    private Logger log = LoggerFactory.getLogger(MerchantController.class);
    @Resource
    private MerchantRepository merchantRepository;
    @GetMapping("/{id}")
    public Merchant getMerchantById(@PathVariable Integer id){
        return merchantRepository.selectByPrimaryKey(id);
    }

    @GetMapping("")
    public Merchant getMerchant(HttpServletRequest request){

        //获取当前用户
        Merchant merchant  =  ShiroUtil.getMerchant(request);
        return merchantRepository.selectByPrimaryKey(merchant.getId());
    }

    @GetMapping("/singleByWechat/{uionid}")
    public Merchant getMerchantByWechat(@PathVariable String uionid, @RequestParam String name){
        return merchantRepository.selectByUnionId(uionid);
    }

    @PostMapping("")
    public ResponseEntity addMerchant(@RequestBody Merchant merchant, HttpServletRequest request){
        if(!"".equals(merchant.getName())){
           log.error("==============================");
            log.error(merchant.getName());
            byte[] b_text=merchant.getName().getBytes();
            for (int i = 0; i < b_text.length; i++)
            {
                if((b_text[i] & 0xF8)== 0xF0){
                    for (int j = 0; j < 4; j++) {
                        b_text[i+j]=0x30;
                    }
                    i+=3;
                }
            }
            String title=new String(b_text);
            merchant.setName(title);

        }
        Integer id = merchantRepository.insert(merchant);
        return new ResponseEntity(merchant, HttpStatus.OK);
    }

    @PutMapping("")
    public ResponseEntity updateMerchant(@RequestBody Merchant merchant, HttpServletRequest request){
        Integer id = merchantRepository.updateByPrimaryKey(merchant);
        return new ResponseEntity(merchant, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity updateMerchant(@PathVariable Integer id, HttpServletRequest request){
        Integer key = merchantRepository.deleteByPrimaryKey(id);
        return new ResponseEntity(key, HttpStatus.OK);
    }
}
